package cn.edu.lingnan.servlet;

import cn.edu.lingnan.pojo.User;
import cn.edu.lingnan.service.userservice;
import cn.edu.lingnan.service.userserviceimp;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

public class AddServlet extends HttpServlet {
    userservice us=new userserviceimp();
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");

        // 获取表单数据
       Integer id = Integer.parseInt(req.getParameter("id"));
        String name = req.getParameter("name");
        System.out.println(" 获取 名字"+name);
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        int age = Integer.parseInt(req.getParameter("age"));
        String gender = req.getParameter("gender");
        String major = req.getParameter("major");
        HttpSession session = req.getSession();
        User byId = us.getById(id);

        System.out.println(byId.getUsername());
        if(byId.getUsername()!=null){
            session.setAttribute("num", 0);
            session.setAttribute("message", "该学号已存在");
        }
        else{
            // 创建学生对象
            User newUser = new User( id, name, username, password, age, gender, major,"","","",0);
            System.out.println(newUser);
            Integer num = us.addUser(newUser);
            // 将结果存储在 Session 中
            session.setAttribute("num", num);
        }
        // 重定向回添加页面以显示结果
        List<User> userList = us.selectall();

        req.getServletContext().setAttribute("userList", userList);
        resp.sendRedirect(req.getContextPath() + "/Addstudent.jsp?submitted=true");
    }
}